// routes/auth/register.js
const express = require('express');
const bcrypt = require('bcrypt');
const pool = require('../../config/pool'); // 使用连接池
const router = express.Router();

// 用户注册接口
router.post('/', async (req, res) => {
    const { username, password } = req.body;
    // 校验username和password存在且长度大于等于5位且不包含特殊字符
    if (!username || !password) {
        return res.status(400).json({
            code: 0,
            message: '用户名和密码不能为空',
            success: false
        });
    }
    if (username.length < 5 || password.length < 5) {
        return res.status(400).json({
            code: 0,
            message: '用户名和密码长度必须大于等于5位',
            success: false
        });
    }
    if (username.includes(' ') || password.includes(' ')) {
        return res.status(400).json({
            code: 0,
            message: '用户名和密码不能包含空格',
            success: false
        });
    }
    // 检查用户是否已存在
    const checkUserQuery = 'SELECT * FROM users WHERE username = ?';
    pool.query(checkUserQuery, [username], async (err, results) => {
        if (err) {
            console.error('数据库错误:', err);
            return res.status(500).send({
                code: 0,
                message: '数据库错误',
                success: false
            });
        }
        if (results.length > 0) {
            return res.status(400).send({
                code: 0,
                message: '用户已存在',
                success: false
            });
        }

        // 密码加密
        const hashedPassword = await bcrypt.hash(password, 10);

        // 插入新用户
        const insertUserQuery = 'INSERT INTO users (username, password) VALUES (?, ?)';
        pool.query(insertUserQuery, [username, hashedPassword], (err, results) => {
            if (err) {
                console.error('数据库错误:', err);
                return res.status(500).send({
                    code: 0,
                    message: '数据库错误',
                    success: false
                });
            }
            res.status(201).send({
                code: 1,
                message: '注册成功',
                success: true
            });
        });
    });
});

module.exports = router;